package com.ddy.test.creditcardmanage.db

import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import com.ddy.test.creditcardmanage.common.Constant
import com.ddy.test.creditcardmanage.dao.CardDao
import com.ddy.test.creditcardmanage.model.Card
import com.ddy.test.creditcardmanage.model.CardRecord

@Database(entities = [Card::class, CardRecord::class], version = Constant.VERSION, exportSchema = false)
abstract class CardDatabase : RoomDatabase() {

    abstract fun cardDao(): CardDao


    companion object{
        @Volatile
        private var instant: CardDatabase? = null

        @Synchronized
        fun getInstance(context: Context?): CardDatabase? {
            if (instant == null) {
                instant = Room.databaseBuilder(context!!.applicationContext, CardDatabase::class.java, Constant.DATABASE_NAME)
                    //默认room不允许在主线程操作数据库，这里设置允许
                    .allowMainThreadQueries().addMigrations(object: Migration(1,2){
                        override fun migrate(database: SupportSQLiteDatabase) {
                            val table = Constant.TABLE_NAME_CARD_RECORD
                            database.execSQL("CREATE TABLE $table(id Long, cardId Long, recordType INTEGER, amount REAL, PRIMARY KEY(`id`))")
                        }

                    }).fallbackToDestructiveMigration()
                    .build()

            }
            return instant
        }

    }
}